//
//  XHPushVCTool.m
//  ShowYork
//
//  Created by hxh on 2021/2/19.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "XHPushVCTool.h"
#import "AppDelegate.h"
#import "TabBarViewController.h"
#import "HomePageDetailViewController.h"
#import "CampusVideoPlayerViewController.h"
#import "MinePageViewController.h"
#import "CommonWebViewController.h"

@implementation XHPushVCTool
SingletonM(XHPushVCTool)

- (void)pushTargetVCWithUrl:(NSString *)url paramUrl:(NSString * __nullable)paramUrl{
    
    UIViewController *vc = [RPAppManager jsd_findVisibleViewController];
    // 除非首末空格
    url = [url cl_removeSpaceString];
    // 解析
    NSDictionary *param = [self dictionaryWithUrlString:url];
    // 首先判断是否是首页 因为有弹框显示全局问题
    // 视频播放页停止视频，退出全屏
    if ([vc isKindOfClass:[VideoPlayerViewController class]]) {
        [((VideoPlayerViewController *)vc) stopVideoPlayer];
    }
    if ([vc isKindOfClass:[CampusVideoPlayerViewController class]]) {
        [((CampusVideoPlayerViewController *)vc) stopVideoPlayer];
    }
    if ([url hasPrefix:@"https://"] || [url hasPrefix:@"http://"]) {
        url = [url stringByRemovingPercentEncoding];
        NSRange range = [url rangeOfString:@"?"];
        if (range.location == NSNotFound) {
            if ([url containsString:@"isApp=true"]) {
                url = [NSString stringWithFormat:@"%@?userId=%@",url,[RPAppManager getCustomerId]];
            }else{
                url = [NSString stringWithFormat:@"%@?isApp=true&userId=%@",url,[RPAppManager getCustomerId]];
            }
        }else{
            if ([url containsString:@"isApp=true"]) {
                url = [NSString stringWithFormat:@"%@&userId=%@",url,[RPAppManager getCustomerId]];
            }else{
                url = [NSString stringWithFormat:@"%@&isApp=true&userId=%@",url,[RPAppManager getCustomerId]];
            }
        }
        CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
        webVC.webUrl = url;
        webVC.isDark = YES;
        [vc.navigationController pushViewController:webVC animated:YES];
        return;
    }
    
    // 主页
    if ([url containsString:@"local://ddup.app/main"]) {
        
//        MinePageViewController *mineVC = [[MinePageViewController alloc]init];
//        [vc.navigationController pushViewController:mineVC animated:YES];
        
//        UIViewController *modalVC = vc;
//        while(modalVC.presentingViewController != nil){
//            modalVC = modalVC.presentingViewController;
//        }
//        [modalVC dismissViewControllerAnimated:NO completion:nil];
//        // 切回tabbar索引1的位置
//        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//        UIViewController * controller = appDelegate.window.rootViewController;
//        TabBarViewController * tabBarController = (TabBarViewController *)controller;
//        // 判断参数是否存在
//        if (param[@"page"] != nil) {
//            [tabBarController setSelectedIndex:[param[@"page"] intValue]];
//        }else{
//            [tabBarController setSelectedIndex:0];
//        }
//        [vc.navigationController popToRootViewControllerAnimated:YES];
//        // 相关modal页面回到根页面  部分页面跳转 push-modal-push
//        [[NSNotificationCenter defaultCenter]postNotificationName:@"popToRootViewControllerByRemoteMessage" object:nil];
    }
    // 课程详情
    if ([url containsString:@"local://ddup.app/lessonDetail"]) {
        [MGJRouter openURL:@"local://ddup/lesson/detail" withUserInfo:@{@"navigationVC":vc.navigationController,@"lessonId":param[@"lesson_id"]} completion:nil];
    }
    // 家长必知
    if ([url containsString:@"local://ddup.app/parentKnow"]) {
        [MGJRouter openURL:@"local://ddup/discover/parentKnow" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
    }
    // 万卷有声
    if ([url containsString:@"local://ddup.app/voicePage"]) {
        [MGJRouter openURL:@"local://ddup.app/voice/voiceList" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
    }
    // 动态详情
    if ([url containsString:@"local://ddup.app/dynamicDetail"]) {
        NSString *postId = param[@"postId"];
        NSMutableDictionary *parma = [NSMutableDictionary dictionary];
        parma[@"userId"] = [RPAppManager getCustomerId];
        parma[@"postId"] = @(postId.intValue);
        parma[@"md5"] = [RPAppManager md5StrWithApi:GetNewPostDetail];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetNewPostDetail) parames:parma success:^(id responseObj) {
            NSArray *resultArray = @[[HomePageItemModel mj_objectWithKeyValues:responseObj[RESPONSE]]];
            
            HomePageItemModel *itemModel = [resultArray firstObject];
            if ([itemModel.deleted boolValue]) {
                [WHToast showMessage:@"该动态已删除" duration:2 finishHandler:nil];
                return;
            }
            
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[kXHItemType] = @(XHPageDetailItemTypeNormal);
            param[kXHScrollUnEnable] = @(YES);
            param[kXHShowUserInfo] = @(YES);
            param[kXHPlatformType] = @(XHPageDetailPlatformTypeSingleDetail);
            param[kXHListSource] = resultArray;
            HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
        
            [vc.navigationController pushViewController:dtlVC animated:YES];
        
        } failure:^(NSError *error) {
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        }];
    }
    if ([url containsString:@"local://ddup.app/schoolList"]) {
        [MGJRouter openURL:@"local://ddup/campus/list" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
    }
    if ([url containsString:@"local://ddup.app/complaint"]) {
        NSNumber *type = @0;
        if ([param[@"type"] isEqualToString:@"lesson"]) {
            type = @1;
        }
        [MGJRouter openURL:@"local://ddup/report" withUserInfo:@{@"navigationVC":vc.navigationController,@"reportId":[NSNumber numberWithString:param[@"id"]] ,@"reportType":@(0)} completion:nil];
    }
    if ([url containsString:@"local://ddup.app/userHome"]) {
        if (![RPAppManager isLogin]) {
            [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
        }else{
            [MGJRouter openURL:@"local://ddup.app/user/loginUserInfo" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
        }
    }
    if ([url containsString:@"local://ddup.app/login"]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
    }
    
    if ([url containsString:@"local://ddup.app/schoolDetail"]) {
        [MGJRouter openURL:@"local://ddup/campus/detail" withUserInfo:@{@"navigationVC":vc.navigationController,@"schId":[NSNumber numberWithString:param[@"id"]]} completion:nil];
    }
    
    if ([url containsString:@"local://ddup.app/lessonHome"]) {
        [MGJRouter openURL:@"local://ddup.app/lesson/lessonList" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
    }
    if ([url containsString:@"local://ddup.app/postHome"]) {
        [MGJRouter openURL:@"local://ddup.app/home/homeList" withUserInfo:@{@"navigationVC":vc.navigationController} completion:nil];
    }
    
    // web 多种情况
    if ([url containsString:@"local://ddup.app/web"]) {
        if (param[@"url"] != nil && [param[@"url"] isKindOfClass:[NSString class]]) {
            NSString *url = param[@"url"];
            url = [url stringByRemovingPercentEncoding];
            NSRange range = [url rangeOfString:@"?"];
            if (range.location == NSNotFound) {
                if ([url containsString:@"isApp=true"]) {
                    url = [NSString stringWithFormat:@"%@?userId=%@",url,[RPAppManager getCustomerId]];
                }else{
                    url = [NSString stringWithFormat:@"%@?isApp=true&userId=%@",url,[RPAppManager getCustomerId]];
                }
            }else{
                if ([url containsString:@"isApp=true"]) {
                    url = [NSString stringWithFormat:@"%@&userId=%@",url,[RPAppManager getCustomerId]];
                }else{
                    url = [NSString stringWithFormat:@"%@&isApp=true&userId=%@",url,[RPAppManager getCustomerId]];
                }
            }
            CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
            webVC.webUrl = url;
            webVC.isDark = YES;
            [vc.navigationController pushViewController:webVC animated:YES];
        }
    }
}

-(NSDictionary *)dictionaryWithUrlString:(NSString *)urlStr
{
    if (urlStr && urlStr.length && [urlStr rangeOfString:@"?"].length == 1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if (array && array.count == 2) {
            NSString *paramsStr = array[1];
            if (paramsStr.length) {
                NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
                NSArray *paramArray = [paramsStr componentsSeparatedByString:@"&"];
                for (NSString *param in paramArray) {
                    if (param && param.length) {
                        NSArray *parArr = [param componentsSeparatedByString:@"="];
                        if (parArr.count == 2) {
                            [paramsDict setObject:parArr[1] forKey:parArr[0]];
                        }
                    }
                }
                return paramsDict;
            }else{
                return nil;
            }
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}

@end
